Home:ALL Converter>Angular 7 injected service throws TypeError after refresh when attempting to call methods

Angular 7 injected service throws TypeError after refresh when attempting to call methods

Ask Time:2020-02-24T01:06:31         Author:Dane Lowrey

Json Formatter

I have a component DevicePage that requests an instance of ServiceAdapter in its constructor, and then uses that ServiceAdapter to request information in ngOnInit(). ServiceAdatper ALSO requests an instance of Service to make http calls and then transform the response into the necessary objects for the DevicePage. My simplified code is:

@Component({
  selector: 'app-device',
  templateUrl: './device.page.html',
  styleUrls: ['./device.page.scss'],
})
export class DevicePage implements OnInit {

  private device: Device;    // beacon used in the HTML template to display info

  constructor(private activatedRoute: ActivatedRoute, private adapter: ServiceAdapter) {
  }

  ngOnInit() {
    // Grab the beacon details
    this.adapter
      .getDevice(this.activatedRoute.snapshot.paramMap.get('id'))
      .subscribe(device=> this.device = device);
  }

}
@Injectable({
    providedIn: 'root'
})
export class ServiceAdapter {

    constructor(private service: Service) {
    }

    getDevice(id: string): Observable<Device> {
        this.service.getDevice(id).pipe(
            map(response => {
                return this.extractDevice(response.data).shift();
            })
        )
    }

    private extractDevice(devices: Device[]) {
        return devices.map(device => <Beacon> {
            id: device.identifier,
            name: device.shadow.name
        });
    }
}
@Injectable({
  providedIn: 'root'
})
export class Service {
  constructor(http: HttpClient) {
    this.http = http;
  }

  getDevice(id): Observable<DevicesResponseV3> {
    return this.http.get<DevicesResponseV3>(URL_DEVICES)
      .pipe(catchError(err => this.handleError(err)));
  }

   private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      console.error(
        `Error response from ${error.url} ` +
        `Backend returned code ${error.status} ` +
        `body was: ${error.message}`);
    }
    // return an observable with a user-facing error message
    return throwError(
      'Something bad happened; please try again later.');
  }
}

When I first arrive at this page from initially opening the app and navigating to it, everything works as expected. However, when I refresh the page, I get the following error: ERROR TypeError: "this.adapter.getDevice(...) is undefined". The service itself is not undefined, I am unsure what is happening.

The contents of my app.module.ts file:

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule,
    IonicModule.forRoot(),
    AppRoutingModule,
    HttpClientModule,
    IonicStorageModule.forRoot(),
    AngularFireModule.initializeApp(environment.firebase, 'herald-client-webapp'),
    AngularFireAuthModule, // imports firebase/auth, only needed for auth features
  ],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

Author:Dane Lowrey,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/60364686/angular-7-injected-service-throws-typeerror-after-refresh-when-attempting-to-cal
yy